<template>
  <div class="room-page-wrapper">
    <div class="room-status-container">
      <div class="search-bar" id="box">
        <h2 class="search-title">更新会议室状态</h2>
        <p class="search-guide">您可以通过名称、类型和状态筛选会议室，点击会议室卡片查看详情</p>
        <form class="search-form" @submit.prevent="handleSearch">
          <div class="form-group">
            <label for="room-name">会议室名称</label>
            <input 
              type="text" 
              id="room-name" 
              v-model="searchForm.name" 
              placeholder="请输入会议室名称"
              class="custom-input"
            >
          </div>
          
          <div class="form-group">
            <label for="room-type">会议室类型</label>
            <select 
              id="room-type" 
              v-model="searchForm.type" 
              class="custom-select"
            >
              <option value="" selected>全部类型</option>
              <option :value="0">教室型</option>
              <option :value="1">圆桌型</option>
            </select>
          </div>    
          
          <div class="form-actions">
            <button type="submit" class="btn btn-primary">查询</button>
            <button type="button" class="btn btn-secondary" @click="resetSearch">刷新</button>
          </div>
        </form>
      </div>

      <div class="room-grid-container">
        <div class="room-grid">
          <div v-for="room in roomList" :key="room.id" class="room-card" @click="handleRoomClick(room)">
            <div class="room-card-header">
              <span class="room-name">{{ room.name }}</span>
              <span class="room-status">
                <el-tag :type="getStatusTagType(room.curStatus)">
                  {{ getStatusText(room.curStatus) }}
                </el-tag>
              </span>
            </div>
            <div class="room-card-type">
              {{ room.type === 0 ? '教室型' : room.type === 1 ? '圆桌型' : '' }}
            </div>
            <img 
              v-if="room.type === 1 && room.seatNum <= 6"
              src="../../assets/pic/TableRoom_Regular.png" 
              class="room-decoration-TableRoom-Regular"
              alt="小型圆桌装饰"
            />
            <img 
              v-if="room.type === 1 && room.seatNum > 6"
              src="../../assets/pic/TableRoom_Big.png" 
              class="room-decoration-TableRoom"
              alt="大型圆桌装饰"
            />
            <img 
              v-if="room.type === 0 && room.seatNum <= 6"
              src="../../assets/pic/ClassRoom_Regular.png" 
              class="room-decoration-ClassRoom-Regular"
              alt="小型教室装饰"
            />
            <img 
              v-if="room.type === 0 && room.seatNum > 6"
              src="../../assets/pic/ClassRoom_Big.png" 
              class="room-decoration-ClassRoom"
              alt="大型教室装饰"
            />
          </div>
        </div>
      </div>

      <!-- 移除分页组件 -->
      <!-- 会议室详情对话框 -->
      <el-dialog
        title="会议室详情"
        v-model="roomDetailVisible"
        width="42%"
        @closed="roomStatusString = ''" 
        @close="selectedDate= ''"
      >
        <div class="room-detail">
          <div class="detail-item">
            <span class="label">会议室名称：</span>
            <span>{{ currentRoom.name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">类型：</span>
            <span>{{ currentRoom.type === 0 ? '教室型' : currentRoom.type === 1 ? '圆桌型' : '' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">面积：</span>
            <span>{{ currentRoom.area }} 平方米</span>
          </div>
          <div class="detail-item">
            <span class="label">座位数：</span>
            <span>{{ currentRoom.seatNum }} 个</span>
          </div>
          <div class="detail-item">
            <span class="label">价格：</span>
            <span>{{ currentRoom.price }} 元/小时</span>
          </div>
          <div class="detail-item">
            <span class="label">当前状态：</span>
            <el-tag :type="getStatusTagType(currentRoom.curStatus)">
              {{ getStatusText(currentRoom.curStatus) }}
            </el-tag>
          </div>
          <div class="detail-item">
          <span class="label">查看会议室状态：</span>
          <el-date-picker
            v-model="selectedDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            :disabled-date="(time) => time.getTime() < Date.now() - 86400000"
            @change="fetchRoomStatus"
          />
        </div>
        <div class="detail-item" v-if="roomStatusString">
          <div class="time-status-grid" style="display: flex; flex-wrap: wrap;">
            <div v-for="(status, index) in roomStatusArray" :key="index" class="time-status-item" style="margin-right: 10px; margin-bottom: 1px;">
              <span class="time-label">{{ index.toString().padStart(2, '0') }}:00 - {{ (index + 1).toString().padStart(2, '0') }}:00</span>
              <el-tag :type="getStatusTagType(Number(status))" size="small" style="margin-left: 5px;">
                {{ getStatusText(Number(status)) }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
        <div class="detail-actions">
          <el-button type="primary" size="small" @click="handleViewDevices(currentRoom)">查看设备</el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleUpdateStatus(currentRoom)"
            :disabled="!canUpdateStatus(currentRoom.status)"
          >更新状态</el-button>
        </div>
      </el-dialog>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[4, 8, 12, 16]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>

      <!-- 设备列表对话框 -->
      <el-dialog
        title="设备列表"
        v-model="deviceDialogVisible"
        width="30%"
      >
        <el-table :data="currentRoomDevices" border style="width: 100%">
          <el-table-column prop="name" label="设备名称"></el-table-column>
          <el-table-column prop="description" label="设备描述"></el-table-column>
        </el-table>
      </el-dialog>

      <!-- 状态更新对话框 -->
      <el-dialog
        title="更新会议室状态"
        v-model="statusDialogVisible"
        width="55%"
        @closed="statusForm.statusString = ''"
        @close="statusForm.date = ''"
      >
        <el-form :model="statusForm" label-width="100px">
          <el-form-item label="选择日期">
            <el-date-picker
              v-model="statusForm.date"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              :disabled-date="(time) => time.getTime() < Date.now() - 86400000"
              @change="initStatusString"
            />
          </el-form-item>

          <el-form-item label="时间段状态" v-if="statusForm.statusString">
            <div class="time-status-grid" style="display: flex; flex-wrap: wrap;">
              <div
                v-for="(status, index) in statusStringArray"
                :key="index"
                class="time-status-item"
                style="margin-right: 10px; margin-bottom: 10px;"
              >
                <span
                  class="time-label"
                  :style="{
                    color:
                      getStatusTagType(Number(status)) === 'success'
                        ? '#67C23A'
                        : getStatusTagType(Number(status)) === 'warning'
                        ? '#E6A23C'
                        : getStatusTagType(Number(status)) === 'primary'
                        ? '#409EFF'
                        : getStatusTagType(Number(status)) === 'danger'
                        ? '#F56C6C'
                        : '#909399'
                  }"
                >
                  {{ index.toString().padStart(2, '0') }}:00 -
                  {{ (index + 1).toString().padStart(2, '0') }}:00
                </span>

                <el-select
                  :model-value="statusStringArray[index]"
                  @update:model-value="onStatusSelectChange(index, $event)"
                  size="small"
                  style="width: 80px; margin-left: 5px;"
                >
                  <el-option label="空闲" :value="0">
                    <el-tag type="success" size="small">空闲</el-tag>
                  </el-option>
                  <el-option label="锁定" :value="1">
                    <el-tag type="warning" size="small">锁定</el-tag>
                  </el-option>
                  <el-option label="预定" :value="2">
                    <el-tag type="primary" size="small">预定</el-tag>
                  </el-option>
                  <el-option label="使用" :value="3">
                    <el-tag type="danger" size="small">使用</el-tag>
                  </el-option>
                  <el-option label="维护" :value="4">
                    <el-tag type="info" size="small">维护</el-tag>
                  </el-option>
                </el-select>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="statusDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitStatusUpdate"
              :disabled="!statusForm.statusString"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import {ElMessage} from 'element-plus'
import request from '../../api/request'
import dayjs from 'dayjs'
import { BlurGradientBg } from "../../components/BlurGradientBg.module.js"


const roomList = ref([])
// 移除分页相关变量
const deviceDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const roomDetailVisible = ref(false)
const currentRoomDevices = ref([])
const currentRoom = ref({})
const selectedDate = ref('')
const roomStatusString = ref('')
const roomStatusArray = computed(() => roomStatusString.value.split(''))

const searchForm = ref({
  name: '',
  type: '',  // 修改为空字符串而不是 null
  status: ''  // 修改为空字符串而不是 null
})

const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',  // 修改为空字符串而不是 null
    status: ''  // 修改为空字符串而不是 null
  }
  handleSearch()
}

const statusForm = ref({
  date: '',
  statusString: ''
})

function onStatusSelectChange(index, newValue) {
  const newArray = [...statusStringArray.value]
  newArray[index] = newValue
  statusStringArray.value = newArray
}

const statusStringArray = computed({
  get: () => statusForm.value.statusString.split('').map(Number),
  set: (newArray) => {
    const newString = newArray.join('')
    statusForm.value.statusString = newString
  }
})

const initStatusString = () => {
  if (!statusForm.value.date || !currentRoom.value.id) {
    statusForm.value.statusString = ''
    return
  }
  statusForm.value.statusString = currentRoom.value.status
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '空闲';
    case 1: return '锁定';
    case 2: return '预定';
    case 3: return '使用';
    case 4: return '维护';
    default: return '';
  }
};

const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'success';
    case 1: return 'warning';
    case 2: return 'primary';
    case 3: return 'danger';
    case 4: return 'info';
    default: return '';
  }
};

const canUpdateStatus = (status) => {
  // 可更新的状态条件
  return true;
};

const getCurrentHourStatus = (status) => {
  const currentHour = new Date().getHours(); // 获取当前小时，范围 0~23
  return status.charAt(currentHour);         // 取出对应的字符
}

const getRoomList = async () => {
  try {
    const response = await request({
      url: '/common/meeting-room',
      method: 'post',
      data: {
        ...searchForm.value,
        date: new Date()
      }
    })
    roomList.value = response.data.records.map(room => {
      const currentHourStatus = getCurrentHourStatus(room.status)
      return {
        ...room,
        curStatus: parseInt(currentHourStatus)
      }
    })
  } catch (error) {
    ElMessage.error('获取会议室列表失败：' + error.message)
  }
}

const handleViewDevices = async (room) => {
  try {
    const response = await request({
      url: '/common/media',
      method: 'get',
      params: {
        meetingRoomId: room.id
      }
    })
    currentRoomDevices.value = response.data
    deviceDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取会议室设备列表失败：' + error.message)
  }
}

const handleRoomClick = (room) => {
  currentRoom.value = room
  roomDetailVisible.value = true
  selectedDate.value = ''
  roomStatusString.value = ''
}

const fetchRoomStatus = async () => {
  if (!selectedDate.value || !currentRoom.value.id){
    roomStatusString.value = ''
    return
  }
  const response = await request({
    url: '/common/meeting-room',
    method: 'post',
    data: {
      id: currentRoom.value.id,
      date: dayjs(selectedDate.value).format("YYYY-MM-DD HH:mm:ss.SSSZ")
    }
  })
  roomStatusString.value = response.data.records[0].status
}

const handleUpdateStatus = (room) => {
  currentRoom.value = room
  statusForm.value.status = room.status
  statusDialogVisible.value = true
}

const submitStatusUpdate = async () => {
  try {
    await request({
      url: '/employee/modify-meeting-room',
      method: 'put',
      data: {
        meetingRoomId: currentRoom.value.id,
        status: statusForm.value.statusString,
        date: dayjs(statusForm.value.date).format("YYYY-MM-DD HH:mm:ss.SSSZ")
      }
    })
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    getRoomList()
  } catch (error) {
    ElMessage.error('状态更新失败：' + error.message)
  }
}

const handleSearch = () => {
  getRoomList()
}

// 移除分页相关方法

onMounted(() => {
  getRoomList()
  
  let colorbg = new BlurGradientBg({ 
    dom: "box", 
    colors: ["#ffcccc","#EDC2F0","#ad8daa","#8f67a2"], 
    loop: true 
  })
})
</script>

<style scoped>
@font-face {
  font-family: "汉仪雅酷黑-85";
  src: url("../../assets/fonts/汉仪雅酷黑-85.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}

.room-page-wrapper {
  display: flex;
  justify-content: center;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32px;
  height: 56px;
  background: #409EFF;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;
  box-shadow: 0 2px 8px #e0e3e7;
}

.navbar-title {
  letter-spacing: 2px;
}

.logout-btn {
  font-size: 14px;
  font-weight: normal;
}

.room-status-container {
  width: 88%;
  max-width: 1700px;
  background: transparent;
  border-radius: 12px;
  position: relative;
}

.search-bar {
  margin-bottom: -220px; /* 增加底部间距，为卡片预留空间 */
  padding: 40px 24px 230px 24px; /* 增加底部内边距 */
  border-radius: 36px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
}

.search-title {
  margin-top: 0;
  margin-bottom: 8px;
  color: #f2f2f2;
  position: relative;
  z-index: 10;
  font-family: "汉仪雅酷黑-85", sans-serif;
  font-size: 36px;
}

.search-guide {
  margin-top: 0;
  margin-bottom: 16px;
  color: #ebebeb;
  font-size: 14px;
  position: relative;
  z-index: 10;
}

.search-bar .el-form {
  position: relative;
  z-index: 10;
  margin-bottom: 30px;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.room-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 50px;
  margin-bottom: 24px;
  position: relative;
  z-index: 10;
  padding: 20px 50px;
}

.room-card {
  background: #fff;  /* 改为纯白色背景 */
  border-radius: 24px;
  padding: 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  cursor: pointer;
  transition: all 0.5s ease;
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  overflow: visible;
}

/* 小教室 */
.room-card:has(img.room-decoration-ClassRoom-Regular) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 大教室 */
.room-card:has(img.room-decoration-ClassRoom) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 小圆桌 */
.room-card:has(img.room-decoration-TableRoom-Regular) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 大圆桌 - 深紫色渐变 */
.room-card:has(img.room-decoration-TableRoom) {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 60%), #fff;
}

/* 悬停效果增强 */
.room-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}

.room-card:has(img.room-decoration-ClassRoom-Regular):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.3) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-ClassRoom):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-TableRoom-Regular):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-card:has(img.room-decoration-TableRoom):hover {
  background: radial-gradient(circle at center, rgba(188, 185, 184, 0.38) 0%, #fff 70%), #fff;
}

.room-card-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.room-name {
  font-family: "汉仪雅酷黑-85", sans-serif;
  font-size: 18px;
  font-weight: 400;
  color: #333;
}

.room-card-type {
  font-size: 14px;
  color: #999;
  margin-top: auto;
}

.room-detail {
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}


.detail-item .label {
  color: #666;
  margin-right: 50px;
  width: 100px;
  color: #606266;
  flex: 0 0 120px; 
}

.time-status-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.time-status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.time-label {
  font-size: 12px;
  color: #666;
}

.detail-actions {
  margin-top: 24px;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: flex-end;
  position: relative;
  z-index: 10;
  justify-content: center;
}

.form-group {
  display: flex;
    flex-direction: row;
    gap: 8px;
    align-items: center;
}

.form-group label {
  color: #f2f2f2;
  font-size: 14px;
  font-weight: 500;
}

.custom-input {
  min-width: 200px;
  padding: 8px 12px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  font-size: 14px;
  transition: all 0.3s ease;
}

.custom-input:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.4);
  background: rgba(255, 255, 255, 0.15);
}

.custom-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.custom-select {
  min-width: 120px;
  padding: 8px 12px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 8.825L1.175 4 2.238 2.938 6 6.7 9.763 2.937 10.825 4z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  padding-right: 32px;
}

.custom-select:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.4);
  background-color: rgba(255, 255, 255, 0.15);
}

.custom-select option {
  background: #2c3e50;
  color: #fff;
}

.form-actions {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.btn:focus {
  outline: none;
}

.btn::after {
  content: '';
  position: absolute;
  inset: 0;
  border: 2px solid transparent;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.btn:focus::after {
  border-color: rgba(255, 255, 255, 0.4);
}

.btn-primary {
  background: #8f67a2;
  color: #fff;
  box-shadow: 0 2px 8px rgba(143, 103, 162, 0.3);
}

.btn-primary:hover {
  background: #7a5089;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(143, 103, 162, 0.4);
}

.btn-primary:active {
  transform: translateY(1px);
  box-shadow: 0 1px 4px rgba(143, 103, 162, 0.3);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 2px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 8px rgba(255, 255, 255, 0.1);
}

.btn-secondary:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.15);
}

.btn-secondary:active {
  transform: translateY(1px);
  background: rgba(255, 255, 255, 0.08);
  box-shadow: 0 1px 4px rgba(255, 255, 255, 0.1);
}

.room-decoration-TableRoom-Regular {
  position: absolute;
  bottom: -8%;
  right: -7%;
  width: 110%;
  height: 110%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-TableRoom-Regular {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-TableRoom {
  position: absolute;
  bottom: -18%;
  right: -19%;
  width: 130%;
  height: 130%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-TableRoom {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-ClassRoom-Regular  {
  position: absolute;
  bottom: -6%;
  right: -5%;
  width: 110%;
  height: 110%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-ClassRoom-Regular {
  transform: scale(1.1);
  opacity: 1;
}

.room-decoration-ClassRoom {
  position: absolute;
  bottom: -16%;
  right: -16%;
  width: 130%;
  height: 130%;
  object-fit: contain;
  pointer-events: none;
  z-index: 1;
  opacity: 1;
  transition: all 0.3s ease;
}

.room-card:hover .room-decoration-ClassRoom {
  transform: scale(1.1);
  opacity: 1;
}
</style>
